package com.zf.shuashua.ui.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.meis.base.mei.adapter.MeiBaseAdapter;
import com.meis.base.mei.base.BaseListFragment;
import com.meis.base.mei.constant.DataConstants;
import com.meis.base.mei.entity.Result;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zf.shuashua.R;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.ListVideo;
import com.zf.shuashua.bean.MoreMeVideoList;
import com.zf.shuashua.ui.custom.Divider3ItemDecoration;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.video.VideoPlayActivity;

import java.util.List;

import io.reactivex.Observable;

@SuppressLint("ValidFragment")
public class MineListVideoFragment extends BaseListFragment<ListVideo.DataBean> {
    private RecyclerView rv;
    private MineListAdapter mAdapter;
    private String user_id;

    public static MineListVideoFragment newInstance(String user_id) {
        Bundle args = new Bundle();
        args.putString("user_id", user_id);
        MineListVideoFragment fragment = new MineListVideoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        View view = setEmptyLayout(R.layout.empty_feed);
        if (getArguments() == null) {
            return;
        }
        user_id = getArguments().getString("user_id");
        if (TextUtils.isEmpty(user_id)) {
            user_id="";
            // ((TextView) view.findViewById(R.id.emptyTitle)).setText(user_id);
        }
        ((TextView) view.findViewById(R.id.emptyTitle)).setText("要发布点内容才能配得上视频达人的称号呀~");
        View emptyBtn = view.findViewById(R.id.emptyBtn);
        if (user_id.equals("") || user_id.equals(Store.getInstance().getuserId())) {
            emptyBtn.setVisibility(View.VISIBLE);
        } else {
            emptyBtn.setVisibility(View.GONE);
        }

        emptyBtn.setOnClickListener(v -> {
            if (!checkLogin()) {
                onJumpVideoSelector();
            }
        });
        super.initView();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_minemyideo;
    }

    private boolean checkLogin() {
        if (!Store.getInstance().isLogin()) {
            startActivity(new Intent(getContext(), LoginActivity.class));
            return true;
        }
        return false;
    }

    @Override
    protected RecyclerView getRecyclerView() {
        rv = findViewById(R.id.rv);
        rv.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rv.addItemDecoration(new Divider3ItemDecoration(getActivity()));
        return rv;
    }

    @Override
    protected MeiBaseAdapter<ListVideo.DataBean> getAdapter() {
        mAdapter = new MineListAdapter(R.layout.likevideo_item, null);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            MoreMeVideoList dataList = new MoreMeVideoList();
            dataList.setDataList(adapter.getData());
            Intent intent = new Intent(getContext(), VideoPlayActivity.class);
            intent.putExtra("position", position);
            intent.putExtra("is_publish", true);
            intent.putExtra("moreMeList", dataList);
            startActivity(intent);
        });
        return mAdapter;
    }

    @Override
    protected Observable<Result<List<ListVideo.DataBean>>> getListObservable(int pageNo) {
        Observable<String> observable = HttpData.getInstance().getListVideo(user_id, pageNo);
        return getListData(observable);
    }

    @Override
    protected void onDataLoaded(int pageNo, Result<List<ListVideo.DataBean>> result) {
        super.onDataLoaded(pageNo, result);
        if (pageNo == DataConstants.FIRST_PAGE && mAdapter.getFooterLayoutCount() < 1) {
            if (user_id.equals("") || user_id.equals(Store.getInstance().getuserId())) {
                View footer = LayoutInflater.from(getActivity()).inflate(R.layout.footer_mine_works_list, rv, false);
                footer.findViewById(R.id.tv_upload).setOnClickListener(v -> {
                    onJumpVideoSelector();
                });
                mAdapter.addFooterView(footer);
            }
        }
    }

    private void onJumpVideoSelector() {
        // 请求权限
        new RxPermissions(this).request(new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE})
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofVideo())
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .selectionMode(PictureConfig.SINGLE)
                                .previewVideo(true)
                                .videoMaxSecond(60)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        ToastUtil.show(getActivity(), "请允许文件读写权限");
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // onResult Callback
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList != null && !selectList.isEmpty()) {
                        String path = "";
                        if (Build.VERSION.SDK_INT < 29) {
                            path = selectList.get(0).getPath();
                        } else {
                            path = selectList.get(0).getAndroidQToPath();
                        }
                        if (!TextUtils.isEmpty(path)) {
                            // 上传视频

                            Intent intent = new Intent(getActivity(), PublishVideoActivity.class);
                            intent.putExtra(PublishVideoActivity.VIDEO_PATH, path);
                            intent.putExtra(PublishVideoActivity.VIDEO_WIDTH, selectList.get(0).getWidth());
                            intent.putExtra(PublishVideoActivity.VIDEO_HEIGHT, selectList.get(0).getHeight());
                            startActivity(intent);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private Observable<Result<List<ListVideo.DataBean>>> getListData(Observable<String> observable) {
        final Result<List<ListVideo.DataBean>> result = new Result<>();
        return observable.map(s -> {
            if (!TextUtils.isEmpty(s)) {
                try {
                    ListVideo likeVideo = ParseJsonUtils.parseData(s, ListVideo.class);
                    result.data = likeVideo.getData();
                } catch (Exception e) {
                }
            }
            return result;
        });
    }

    @Override
    public boolean canLoadMore() {
        return true;
    }

    @Override
    public boolean canPullToRefresh() {
        return false;
    }
}